package by.ostrovsky.webhousingsystem.dao.implementation;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import by.ostrovsky.webhousingsystem.dao.implementation.idao.IOperateDAO;
import by.ostrovsky.webhousingsystem.dao.implementation.idao.IReadDAO;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.HibernateUtil;
import by.ostrovsky.webhousingsystem.hibernate.entity.Employee;

public class MySQLEmployeDAO implements IOperateDAO<List<Employee>, Boolean>,
		IReadDAO<Employee>{
	private static Logger logger = Logger.getLogger(MySQLEmployeDAO.class);

	@Override
	public List<Employee> readAll() throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			@SuppressWarnings("unchecked")
			List<Employee> list = session.createCriteria(Employee.class).list();
			session.getTransaction().commit();
			session.close();

			return list;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean update(List<Employee> employe) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (Employee emp : employe) {
				try {
					session.update(emp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean create(List<Employee> employee) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (Employee emp : employee) {
				try {
					session.save(emp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean delete(List<Employee> list) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (Employee emp : list) {
				try {
					session.delete(emp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Employee read(Employee object) throws CommonException {
		// TODO Auto-generated method stub
		return null;
	}
}
